package com.sdses.weather.factory;

import com.sdses.weather.config.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
@Slf4j
public class WeatherApiProviderRegistry {

    private final Map<String, WeatherApiProvider> providers = new HashMap<>();

    // 通过构造函数注入所有 Spring 管理的 WeatherApiProvider 实现
    public WeatherApiProviderRegistry(List<WeatherApiProvider> providerList) {
        for (WeatherApiProvider provider : providerList) {
            String name = provider.getProviderName();
            if (name != null && !name.trim().isEmpty()) {
                providers.put(name.toLowerCase(), provider);
            }
        }
        log.info("已注册天气API厂商: {}", providers.keySet());
    }

    /**
     * 根据配置名称获取 provider
     */
    public WeatherApiProvider getProvider(String providerName) {
        WeatherApiProvider provider = providers.get(providerName.toLowerCase().trim());
        if (provider == null) {
            throw new BusinessException("未找到厂商实现: " + providerName);
        }
        return provider;
    }

    public Collection<WeatherApiProvider> getAllProviders() {
        return providers.values();
    }
}
